var prefix = jsctx + "/acctTenantOperator";

var acctWithdrawApply = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });
    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPageAcctWithdrawApply",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 20,
                    pageList: [20],
                    pageNumber: 1,
                    sidePagination: "server",
                    paginationShowPageGo: true,
                    height: h,
                    rightFixedColumns: false,
                    showColumns: false,
                    queryParams: function (params) {
                        return {
                            limit: params.limit,
                            offset: (params.offset / params.limit) + 1,
                            tenantOperatorCode: $('#tenantOperatorCode').val(),
                            operatorName: $('#operatorName').val(),
                            loginName: $('#loginName').val(),
                            outTradeNo: $('#outTradeNo').val(),
                            stationName: $('#stationName').val(),
                            status: $('#status').val(),
                        };
                    },
                    columns: [
                        {
                            title: '#', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'operatorName', title: '分销商名称', align: 'left', width: '100'},
                        {field: 'loginName', title: '分销商账号', width: '100'},
                        {field: 'outTradeNo', title: '交易订单号', width: '100'},
                        {field: 'withdrawAmount', title: '提现金额', width: '100'},
                        {field: 'withdrawElecAmount', title: '提现电费金额', width: '110'},
                        {field: 'withdrawServiceAmount', title: '提现服务费金额', width: '130'},
                        {field: 'withdrawServiceCharge', title: '提现手续费', width: '120', align: 'right',},
                        {
                            field: 'transferMethod', title: '结算转账方式', width: '120', align: 'right',
                            formatter: function (value, row, index) {
                                if (row.transferMethod == '0') {
                                    return '线上转账'
                                } else if (row.transferMethod == '1') {
                                    return '线下转账'
                                }
                            }
                        },
                        {
                            field: '', title: '收款账户', align: 'left', width: '100',
                            formatter: function (value, row, index) {
                                if (row.acctBankAccount != '' && row.acctBankAccount != null) {
                                    return row.acctBankAccount;
                                } else if (row.alipayUserId != '') {
                                    return row.alipayUserId;
                                }
                            }
                        },
                        {
                            field: '', title: '收款账户名称', align: 'left', width: '100',
                            formatter: function (value, row, index) {
                                if (row.accountName != '' && row.accountName != null) {
                                    return row.accountName;
                                } else if (row.alipayUserName != '') {
                                    return row.alipayUserName;
                                }
                            }
                        },
                        {
                            field: '', title: '对应账单', width: '300', align: 'left',
                            formatter: function (value, row, index) {
                                var acctBillOrderList = row.acctBillOrderList;
                                var acctBillOrder = '';
                                for (var i = 0; i < row.acctBillOrderList.length; i++) {
                                    acctBillOrder += '账单' + (i + 1) + ':' + '电费' + acctBillOrderList[i].elecAcctAmount + '元' + '/服务费' + acctBillOrderList[i].serviceAcctAmount + '元;' + acctBillOrderList[i].billStartTime + '至' + acctBillOrderList[i].billEndTime + ';' + acctBillOrderList[i].stationName + ';' + '<br>'
                                }
                                // acctBillOrderList[i].factAmount
                                return acctBillOrder;
                            }
                        },
                        {field: 'createdTime', title: '提交时间', width: '100'},
                        {field: 'remark', title: '备注', width: '100'},
                        {
                            field: '', title: '提现状态', width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                if (row.status == '0') {
                                    return '<span >待审核</span>';
                                } else if (row.status == '1') {
                                    return '<span >已处理</span>';
                                } else if (row.status == '2') {
                                    return '<span >驳回</span>';
                                } else if (row.status == '3') {
                                    return '<span >提现中</span>';
                                } else if (row.status == '4') {
                                    return '<span >已到账</span>';
                                } else if (row.status == '5') {
                                    return '<span >提现失败</span>';
                                }
                            }
                        },
                        {field: '', title: '失败原因', width: '100'},
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '300', align: 'center',
                            formatter: function (value, row, index) {

                                var a = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="查看发票" onclick="acctWithdrawApply.invoiceModal(\'' + row.withdrawApplyId + '\')">查看发票</a> ';

                                var b = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="详情" onclick="acctWithdrawApply.detailAcctWithdrawApply(\''
                                    + row.withdrawApplyId
                                    + '\')">详情</a> ';

                                var c = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="通过" onclick="acctWithdrawApply.updateStatusForSucess(\''
                                    + row.withdrawApplyId
                                    + '\')">通过</a> ';

                                var d = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="驳回" onclick="acctWithdrawApply.updateStatusForFail(\''
                                    + row.withdrawApplyId
                                    + '\')">驳回</a> ';

                                var e = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="已转账" onclick="acctWithdrawApply.updateStatusForSucess(\''
                                    + row.withdrawApplyId
                                    + '\')">已转账</a> ';

                                if (row.status == '0') {
                                    if (row.alipayUserId == null || row.alipayUserId == '') {
                                        return a + b + d + e;
                                    }
                                    return a + b + c + d;
                                } else {
                                    return a + b;
                                }


                            }
                        }
                    ]
                });
    }

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }

    function goBack() {
        location.href = prefix + "/index";
    }

    function detailAcctWithdrawApply(withdrawApplyId) {
        location.href = prefix + "/detailAcctWithdrawApply/" + withdrawApplyId;
    }

    function updateStatusForFail(withdrawApplyId) {
        $('#exampleModal').modal('show')
        $("#submitForm").unbind("click").bind("click", function () {
            var formData = new FormData();
            formData.append("remark", $("#rejectRemark").val());
            formData.append("withdrawApplyId", withdrawApplyId);
            formData.append("status", "2");
            $.ajax({
                url: prefix + "/updateAcctWithdrawApplyStatus",
                type: "post",
                data: formData,
                dataType: "json",
                processData: false, // 告诉jQuery不要去处理发送的数据，用于对data参数进行序列化处理 这里必须false
                contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                    }

                }
            })
        })
    }

    var isajaxsendForSucess = true;

    function updateStatusForSucess(withdrawApplyId) {

        layer.confirm('确认通过？', {
            btn: ['确定', '取消']
        }, function (index) {
            if (isajaxsendForSucess) {
                $.ajax({
                    url: prefix + "/updateAcctWithdrawApplyStatus",
                    type: "post",
                    data: {
                        'withdrawApplyId': withdrawApplyId,
                        'status': '1'
                    },
                    beforeSend: function () {
                        isajaxsendForSucess = false;
                    },
                    success: function (data) {
                        isajaxsendForSucess = false;
                        setTimeout(function () {
                            isajaxsendForSucess = true;
                        }, 1500)
                        layer.close(index);
                        if (data.status == 200) {
                            layer.msg("操作成功");
                            reLoad();
                        } else {
                            layer.msg(data.message);
                        }
                    }
                });
            }
        })

    }

    function invoiceModal(withdrawApplyId) {
        $.ajax({
            url: prefix + "/listAcctWithdrawInvoice",
            type: "GET",
            data: {
                'withdrawApplyId': withdrawApplyId,
            },
            success: function (data) {
                $("#invoiceModal ul").html('');
                var str = '';
                for (var i = 0; i < data.length; i++) {
                    str += "<li href='" + data[i].invoiceImg + "'>" +
                        "<a href='" + data[i].invoiceImg + "' class='fileLink' target='myFrameName'>" +
                        "<img src='../statics/img/newEdition/pdf_1.png'>" +
                        "<div>附件" + (i + 1) + "</div>" +
                        "</a>" +
                        "</li>"
                }
                if (data[0].invoiceImg.indexOf("pdf") > 0) {
                    $("#myFrameId").attr("src", data[0].invoiceImg);
                    $(".imgWrap").addClass("hide");
                    $("#myFrameId").removeClass("hide");
                } else if (data[0].invoiceImg.lastIndexOf("/") == 6) {
                    $(".imgWrap img").addClass("hide");
                    $("#myFrameId").attr("src","");
                } else {
                    $(".imgWrap").removeClass("hide");
                    $(".imgWrap img").attr("src", data[0].invoiceImg).removeClass("hide");
                    $("#myFrameId").addClass("hide");
                }
                $("#invoiceModal ul").append(str);
            },
        });
        setTimeout(function () {
            layer.open({
                type: 1,
                title: '发票预览（附件1）',
                closeBtn: false,
                shade: 0.4,
                shift: 7,
                maxWidth: '622px',
                shadeClose: true,
                content: $("#invoiceModal"),
                btn: ['取消'],
                btn1: function (index) {//layer.msg('yes');    //取消
                    layer.close(index)
                },

            });
        }, 100)


    }


    function exportAcctWithdrawApply() {
        $.fileDownload(prefix + "/exportAcctWithdrawApply", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                tenantOperatorCode: $("#tenantOperatorCode").val().trim(),
                operatorName: $("#operatorName").val().trim(),
                loginName: $("#loginName").val().trim(),
                outTradeNo: $("#outTradeNo").val().trim(),
                stationName: $("#stationName").val().trim(),
                status: $("#status").val().trim(),
                // count: $("#count").val().trim() == '' ? 0 : $("#count").val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    // invoiceModal()

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        detailAcctWithdrawApply: detailAcctWithdrawApply,
        updateStatusForSucess: updateStatusForSucess,
        updateStatusForFail: updateStatusForFail,
        invoiceModal: invoiceModal,
        exportAcctWithdrawApply: exportAcctWithdrawApply
    };
})();
